package com.ftz.examinationsystem.controller;

import com.alibaba.excel.EasyExcel;
import com.ftz.examinationsystem.pojo.*;
import com.ftz.examinationsystem.service.UserService;
import com.ftz.examinationsystem.util.DateUtils;
import com.ftz.examinationsystem.util.ExcelListener;
import com.ftz.examinationsystem.util.JsonResult;
import com.ftz.examinationsystem.util.Result;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.security.timestamp.TSRequest;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.*;

@Controller
public class UserController {
    @Autowired
    UserService userService;

//    @GetMapping("/addRoom")
//    public String addRoom(){
//        return "addRoom";
//    }
//
//    @GetMapping("/roomList")
//    public String showRoom(){
//        return "RoomList";
//    }

    /**
     * 导入Excel表格接口
     * @param file Excel文件
     * @return
     * @throws IOException
     */
    @PostMapping("/importexcel")
    @ResponseBody
    public Result<Void> importexcel(@RequestPart(value = "file") MultipartFile file,String cname)throws IOException {
        int sum=0;
        //获取表头验证是否符合要求
        String tablecell[]={"学号","中文姓名","专业","授课教师","课程代码","学科类别","校区"};
        List<String> list=new ArrayList<>();
        InputStream stream=file.getInputStream();
        try {
            Workbook workbook= WorkbookFactory.create(stream);
            Sheet rs = workbook.getSheetAt(0);
            Row row = rs.getRow(0);
            int colcount = rs.getRow(0).getLastCellNum();
            for(int i=0;i<colcount;i++){
                Cell cell = row.getCell(i);
                String cellValue=cell.getStringCellValue().trim();
                list.add(cellValue);
            }
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }

        if(list.size()!=tablecell.length){
            return new Result<>(401,"表头长度错误！");
        }
        for(int i=0;i<list.size();i++){
            if(list.get(i).equals(tablecell[i])) sum++;
        }
        if(sum!=list.size()){
            return new Result<>(402,"表头格式错误！");
        }
        System.out.println(cname);
        if(cname.equals("")){
            return new Result<>(400,"请先输入课程名");
        }else {
            EasyExcel.read(file.getInputStream(), Student.class,new ExcelListener(userService)).sheet().doRead();
            userService.updateStu(cname);
            return new Result<>(0,"成功");
        }
    }

    /**
     * 从数据库中读取所有学生信息
     * @return
     */
    @RequestMapping("/showStu")
    @ResponseBody
    public Result<List<Student>> showStu(Page page){
        List<Student> students=userService.showAll(page);
        Long count = userService.countStu(page);
        return new Result<>(0,"读取成功",students,count);
    }

    /**
     * 添加机房
     * @param room 机房信息
     * @return
     */
    @RequestMapping("/addRoom/add")
    @ResponseBody
    public JsonResult<Void> addRoom(Room room){
        /*前端页面传进来的参数aempty或pempty只要为空设置为0*/
        if(room.getAempty()==null) room.setAempty(0);
        if(room.getPempty()==null) room.setPempty(0);
        int result = userService.addRoom(room);
        if(result>=1){
            return new JsonResult<>(200,"添加机房成功！");
        }else {
            return new JsonResult<>(400,"添加机房失败！");
        }
    }

    /**
     * 根据条件查询机房
     * @param roomQuery 查询条件
     * @return
     */
    @RequestMapping("/showRoom")
    @ResponseBody
    public Result<List<Room>> getRoomList(RoomQuery roomQuery){
        System.out.println(roomQuery);
        List<Room> roomList = userService.getRoomList(roomQuery);
        Long count = userService.countRoomList(roomQuery);
        return new Result<>(0,"success",roomList,count);
    }

    /**
     * 点击编辑获取机房信息并进行修改
     * @param id 机房id
     * @param model 查询到的信息存储到model中
     * @return
     */
    @RequestMapping("/room/find/{id}")
    public String editRoom(@PathVariable("id")Integer id, Model model){
        Room room = userService.getRoomById(id);
        model.addAttribute("room",room);
        return "room/roomEdit";
    }

    /**
     * 修改机房信息
     * @param room 修改条件
     * @return
     */
    @RequestMapping("/room/edit")
    @ResponseBody
    public JsonResult<Void> updateRoom(Room room){
        if(room.getAempty()==null) room.setAempty(0);
        if(room.getPempty()==null) room.setPempty(0);
        userService.updateRoom(room);
        return new JsonResult<>(200,"修改机房成功！");
    }

    /**
     * 删除机房
     * @param ids 机房号的集合
     * @return
     */
    @RequestMapping("/room/delete/{ids}")
    @ResponseBody
    public JsonResult<Void> deleteRooms(@PathVariable("ids")String ids){
        userService.deleteRooms(ids);
        return new JsonResult<>(200,"删除机房成功！");
    }

    /**
     * 查询所有学生信息（没有分页）
     * @return
     */
    @RequestMapping("student/queryAll")
    @ResponseBody
    public Result<List<Student>> showStus(){
        List<Student> students=userService.showStu();
        Long count = Long.valueOf(students.size());
        return new Result<>(0,"读取成功",students,count);
    }

    /**
     * 删除所有学生信息
     * @return
     */
    @RequestMapping("student/delete")
    @ResponseBody
    public Result<Void> deleteStu(){
        userService.deleteStus();
        return new Result<>(200,"删除成功！");
    }

    /**
     * 根据考试配置进行机房考试的分配
     * @param arrangeParam 前端的参数
     */
    @RequestMapping("exam/arrange")
    @ResponseBody
    public JsonResult<List<String>> arrange(ArrangeParam arrangeParam){
        System.out.println(arrangeParam);
        List<String> strings = userService.arrangerRoom(arrangeParam);
//        return result>=1?new JsonResult<>(200,"分配成功！"):new JsonResult<>(400,"分配失败！");
        if(strings.size()>0){
            return new JsonResult<>(400,"分配失败",strings);
        }else {
            return new JsonResult<>(200,"分配成功！");
        }
    }

    //根据机房号查询在哪个校区
    public int isCampus(Object id){
        List<Room> rooms = userService.queryRoom();
        for(int i=0;i<rooms.size();i++){
            Room room = rooms.get(i);
            if(room.getRoomId().equals(id)){
                return room.getCampus();
            }
        }
        return 0;
    }

    //根据机房号查询容量
    public int roomnumber(Object id){
        List<Room> rooms = userService.queryRoom();
        for(int i=0;i<rooms.size();i++){
            Room room = rooms.get(i);
            if(room.getRoomId().equals(id)){
                return room.getRoomCap();
            }
        }
        return 0;
    }

    /**
     * 考试安排统计显示（简单的显示机房使用情况）
     * 显示的是某一门课程所有考试时间的情况
     * @param course
     * @return
     */
    @RequestMapping("exam/unifiedArrage2")
    @ResponseBody
    public JsonResult<showall> arrange2(String course){
        int hua=0,zhe=0,tian=0;
        List<Integer> integers = userService.countStus(course);
        List<String> selectDate = userService.selectDate(course);
        List<Map<Object, Object>> mapList = userService.selectIdDate(course);
        List<showinfo> showinfos = new ArrayList<>();
        List<Integer> rooms = userService.countRooms();
        int sum=0,count=0;
        for(Integer i:integers){
            sum+=i;
        }
        for(Integer i:rooms){
            count+=i;
        };
        for(int i=0;i<selectDate.size();i++){
            showinfo s = new showinfo();
            s.setTimes(selectDate.get(i));
            for(int j=0;j<mapList.size();j++){
                Map<Object, Object> objectMap = mapList.get(j);
                String examDate = DateUtils.convertDate2String("yyyy-MM-dd", (Date) objectMap.get("ExamDate"));
                if(examDate.equals(selectDate.get(i))){
                    if(isCampus(objectMap.get("RoomId"))==1) hua++;
                    if(isCampus(objectMap.get("RoomId"))==2) zhe++;
                    if(isCampus(objectMap.get("RoomId"))==3) tian++;
                }
            }
            s.setHua(hua);
            s.setZhe(zhe);
            s.setTian(tian);
            s.setTotal(hua+zhe+tian);
            showinfos.add(s);
            hua=0;zhe=0;tian=0;
        };

        List<showinfo2> showinfos2 = new ArrayList<>();
        int huas=0,zhes=0,tians=0;
        for(int j=0;j<selectDate.size();j++){
            showinfo2 s = new showinfo2();
            s.setTimes(selectDate.get(j));
            List<Map<Object, Object>> list = userService.selectRoomNumber(course, selectDate.get(j));
            System.out.println(list);
            for(int t=0;t<list.size();t++){
                Map<Object, Object> objectMap = list.get(t);
                int counts = roomnumber(objectMap.get("RoomId"));
                String numbers = String.valueOf(objectMap.get("numbers"));
                if(isCampus(objectMap.get("RoomId"))==1) huas+=counts*Integer.parseInt(numbers);
                if(isCampus(objectMap.get("RoomId"))==2) zhes+=counts*Integer.parseInt(numbers);
                if(isCampus(objectMap.get("RoomId"))==3) tians+=counts*Integer.parseInt(numbers);
            }
            s.setHua(huas);
            s.setZhe(zhes);
            s.setTian(tians);
            s.setTotal(huas+zhes+tians);
            showinfos2.add(s);
            huas=0;zhes=0;tians=0;
        }
        System.out.println(showinfos2);
        List<Integer> countStus = userService.countStus(course);
        showall showall = new showall(showinfos,showinfos2,countStus);
        return new JsonResult<>(200,showall);
    }

    /**
     * 查询考场机房
     * @param query
     * @return
     */
    @RequestMapping("/showeRoom")
    @ResponseBody
    public Result<List<OrderRoom>> geteRoomList(eRoomQuery query){
        System.out.println(query);
        List<OrderRoom> orderRooms = userService.geteRoomList(query);
        Long counteRoomList = userService.counteRoomList(query);
        return new Result<>(0,"success",orderRooms,counteRoomList);
    }

    /**
     * 删除已安排考试机房
     * @param ids 机房号的集合
     * @return
     */
    @RequestMapping("/eRoom/delete/{ids}")
    @ResponseBody
    public JsonResult<Void> deleteeRooms(@PathVariable("ids")String ids){
        System.out.println(ids);
        int result = userService.deleteERooms(ids);
        return result>=1?new JsonResult<>(200,"删除考试机房成功！"):new JsonResult<>(400,"删除失败！");
    }

    @RequestMapping("/eRoom/deleteAll")
    @ResponseBody
    public JsonResult<Void> deleteAllRoom(){
        int result = userService.deleteRoom();
        String message1="删除所有考试机房信息成功！";
        String message2="删除中出现异常，请再试一次吧！";
        return result==0?new JsonResult<>(200,message1):new JsonResult<>(400,message2);
    }

    /**
     * 按条件查询考试学生信息
     * @param query
     * @return
     */
    @RequestMapping("/showArrangeStu")
    @ResponseBody
    public Result<List<StuDetail>> getArrangeStu(eRoomQuery query){
        System.out.println(query);
        List<StuDetail> arrangeDetail = userService.getStuArrangeDetail(query);
        Long aLong = userService.countArrangeDetaile(query);
        return new Result<>(0,"success",arrangeDetail,aLong);
    }

    /**
     * 删除所有考生信息
     * @return
     */
    @RequestMapping("/stu/deleteAll")
    @ResponseBody
    public JsonResult<Void> deleteAllStu(){
        int result = userService.deleteArrangeStu();
        String message1="删除所有考试学生信息成功！";
        String message2="删除中出现异常，请再试一次吧！";
        return result==0?new JsonResult<>(200,message1):new JsonResult<>(400,message2);
    }

    @RequestMapping("/selectUnState")
    @ResponseBody
    public Result<List<Student>> selectUnState(String cname){
        System.out.println(cname);
        List<Student> students = userService.selectUnState(cname);
        return new Result<>(0,"success",students);
    }

    /**
     * 个别安排
     * @param inidivalArrange
     * @return
     */
    @RequestMapping("arrange/individual")
    @ResponseBody
    public JsonResult<Void> individual(InidivalArrange inidivalArrange){
        System.out.println(inidivalArrange);
        int result = userService.individualArrange(inidivalArrange);
        //时间段重合但单独安排的人数和已安排人数超过考场可以考试人数，不能插入
        if(result==1){
            return new JsonResult<>(300,"人数超过机房容量限制！");
        }
        //可以插入(时间段重合直接可以插入学生)
        if(result==2){
            return new JsonResult<>(200,"时间段重合且人数满足安排条件！");
        }
        //时间段存在交集不能插入
        if(result==-1){
            return new JsonResult<>(400,"此时间段存在其他考试！");
        }
        //可以插入（时间段和学生同时插入）
        if(result==3){
            return new JsonResult<>(100,"此时间段空闲，可以安排！");
        }
        return new JsonResult<>(0,"出现异常！");
    }

    /**
     * 清除考场界面左边显示
     * @param cname
     * @param roomAddr
     * @return
     */
    @RequestMapping("/ClearRoomStu")
    @ResponseBody
    public Result<List<ERorder>> ClearRoomStu(String cname,String roomAddr){
//        System.out.println(cname+" "+roomAddr);
        List<ERorder> eRorderList = userService.selectERorderByRoomAddr(cname, roomAddr);
//        System.out.println(eRorderList);
        return new Result<>(0,"success",eRorderList);
    }

    /**
     * 清除考场界面右边显示
     * @param examDate
     * @param erordId
     * @param etype
     * @return
     */
    @RequestMapping("/ClearRoomStuR")
    @ResponseBody
    public Result<List<EStudent>> ClearRoomStuR(String examDate,String erordId,String etype){
        System.out.println("examDate:"+examDate+" erordId:"+erordId+" etype:"+etype);
        String[] strings = examDate.split(" ");
        examDate=strings[0];
//        System.out.println(examDate);
        List<EStudent> eStudents = userService.selectByIdDate(etype, erordId, examDate);
        return new Result<>(0,"success",eStudents);
    }

    /**
     * 清除指定考场指定学生
     * @param ids
     * @param cname
     * @return
     */
    @RequestMapping("/clearStu")
    @ResponseBody
    public Result<Void> clearStu(String ids,String cname,String erordId,String examDate,int cnt){
        System.out.println("ids:"+ids+"  cname:"+cname+" erordId:"+erordId+" examDate:"+examDate+" cnt:"+cnt);
        //根据ids和cname删除estudent表中考生信息；
        int result = userService.deleteStusById(ids, cname);
        //改变eorder表中enumber的数量；
        int updatanumber = userService.updatanumber(cname, erordId, examDate, cnt);
        //修改student中state的状态为0
        int state = userService.updateStateByIdCourse2(ids, cname);
        if(result>0&&updatanumber>0&&state>0){
            return new Result<>(200,"success");
        }else {
            return new Result<>(400,"fail");
        }
    }

    /**
     * 清除指定考场和所有学生
     * @param eRorders
     * @return
     */
    @PostMapping("/clearRoomStu")
    @ResponseBody
    public Result<Void> clearRoomStu(@RequestBody List<ERorder> eRorders){
        System.out.println(eRorders);
        int a=0;
        for(ERorder eRorder:eRorders){
            String erorder=eRorder.getEROrdId();
            String examDate = DateUtils.convertDate2String("yyyy-MM-dd", eRorder.getExamDate());
            String cname = eRorder.getEtype();
            //根据EROrdId，ExamDate，Etype删除erorder中考场信息
            int i = userService.deleteerorder(erorder, examDate, cname);
            //再根据EROrdId，ExamDate，Etype删除estudent中考生信息
            int i1 = userService.deleteStudents(erorder, examDate, cname);
            a++;
        }
        if(a==eRorders.size()){
            return new Result<>(200,"success");
        }else {
            return new Result<>(400,"fail");
        }
    }

    /**
     * 根据机房地址获取容量
     * @param roomAddr
     * @return
     */
    @RequestMapping("/cntRoom")
    @ResponseBody
    public JsonResult<Integer> clearRoomStu(String roomAddr){
        int cnt = userService.cntByName(roomAddr);
        return new JsonResult<>(0,cnt);
    }

    @RequestMapping("export/estudent")
    @ResponseBody
    public Result<List<StuDetail>> queryestudent(){
        List<StuDetail> eStudents = userService.selectAllestudent();
        Long count= Long.valueOf(eStudents.size());
        return new Result<>(0,"读取成功",eStudents,count);
    }

    @RequestMapping("export/allroom")
    @ResponseBody
    public Result<List<OrderRoom>> ueryAllRoom(){
        List<OrderRoom> orderRooms = userService.selectAllRoom();
        Long count= Long.valueOf(orderRooms.size());
        return new Result<>(0,"导出成功",orderRooms,count);
    }

    /**
     * 交换学生考场
     * @param course
     * @param leftAddr
     * @param rightAddr
     * @param leftroom
     * @param rightroom
     * @param leftnumbers
     * @param rightnumbers
     * @param leftStr
     * @param rightStr
     * @return
     */
    @RequestMapping("/changeStu")
    @ResponseBody
    public Result<Void> changeStu(String course,String leftAddr,String rightAddr,String leftroom,String rightroom,int leftnumbers,
                                  int rightnumbers,String leftStr,String rightStr){
        System.out.println("course："+course+" leftAddr："+leftAddr+" rightAddr："+rightAddr+" leftroom："+leftroom+" rightroom："+rightroom+" leftnumbers："+leftnumbers+" rightnumbers："+rightnumbers+" leftStr："+leftStr+" rightStr："+rightStr);
        int result = userService.changeStus(course, leftroom, rightroom, rightStr,leftnumbers,rightnumbers);
        return result==1?new Result<>(200,"调换成功！"):new Result<>(300,"出错啦！请重新调换！");
    }
}
